<?php
namespace Admin\Controller;

use Admin\Model\Page;
use Think\Exception;

class AdminController extends BaseController
{
    public function __construct($baseModel)
    {
        parent::__construct(D('Admin'));
    }

    private static $_validate = array(
        array('username', 'require', '账号不能为空！', 1, 'regex', 3),
        array('username', '1,30', '账号的值最长不能超过 30 个字符！', 1, 'length', 3),
        array('password', 'require', '密码不能为空！', 1, 'regex', 3),
        array('password', '1,32', '密码的值最长不能超过 32 个字符！', 1, 'length', 3),
        array('is_use', 'number', '是否启用 1：启用0：禁用必须是一个整数！', 2, 'regex', 3),
    );

    public function index()
    {
        $model = D('Admin');
        //构建查询条件
        $pagesize = 10;
        $search = I('search', '', 'htmlspecialchars');
        $pagenumber = I('pagenum', '');
        if (empty($pagenumber) || $pagenumber <= 0)
            $pagenumber = 1;
        if ($search != '') {
            $map['username'] = array('like', '%' . $search . '%');
        }
        $map['is_use'] = 1;
        //查询
        $list = $model->getByConditionPage($map,$pagenumber,$pagesize);
        $recordcount = $model->where($map)->count();
        //封装分页对象
        $page = new Page($pagenumber, $recordcount, $pagesize);
        $page = (array)$page;//转换为数组

        //显示数据
        $this->assign('page', $page);
        $this->assign('search', $search);
        $this->assign('pagenumber', $pagenumber);
        $this->assign('list', $list);
        $this->assign('user',$this->getAdmin());
        $this->assign('recordcount', $recordcount);
        $this->display();
    }


    public function addUI()
    {
        parent::addUI();
    }

    //添加方法回调
    protected function doAddBefore($data)
    {
        $Admin = D('Admin');
        $where['username'] = ':username';
        $count = $Admin->where($where)->bind($where['username'], $data['username'])->count();
        if ($count >= 1)
            parent::retJson(false, ' 添加失败，用户名称不能重复');
    }

    public function add()
    {
        parent::add(self::$_validate);
    }

    public function delete($id)
    {
        parent::delete($id);
    }

    public function doDeleteBefore($id)
    {
        try {
            $this->deleteCascade($id);
        } catch (Exception $e) {
            $this->baseModel->rollback();
            $this->retJson(false, '删除失败,无法级联删除');
        }

    }

    public function authorizeUI($id)
    {
        $Admin = M('Admin');
        $Role = D('Role');
        $where['id'] = ':id';
        $Admin->where($where)->bind($where['id'], $id)->find();
        $roleList = $Role->select();
        $adminRoleList = $Role->getListByAdmin($id);
        for ($i = 0; !empty($roleList) && $i < count($roleList); $i++) {
            for ($j = 0; !empty($adminRoleList) && $j < count($adminRoleList); $j++) {
                if ($roleList[$i]['id'] == $adminRoleList[$j]['id']) {
                    $roleList[$i]['selected'] = 'selected';
                }
            }
        }
        $this->bcItemPush('用户授权', U('Admin/authorizeUI/'.$id));
        $this->assign('user', $Admin->data());
        $this->assign('roleList', $roleList);
        $this->display('authorize');
    }

    public function authorize()
    {
        $Admin = M('Admin');
        $Admin->startTrans();//开启事务
        try {
            $adminId = I('post.id');
            $is_use = I('post.is_use');
            $this->deleteCascade($adminId);
            $role_ids = I('post.role_ids');
            $this->insertCascade($role_ids, $adminId);
            $this->updateAdmin($Admin, $adminId, $is_use);
            $Admin->commit();
            parent::retJson(true, '授权成功');
        } catch (Exception $e) {
            $Admin->rollback();//事务回滚
            parent::retJson(false, '授权失败，出现未知错误');
        }
//        $AdminRole->where()
    }

    /**
     * @param $Admin
     * @param $adminId
     * @param $is_use
     * @param 是否修改成功
     */
    private function updateAdmin($Admin, $adminId, $is_use)
    {
        $where['id'] = ':id';
        $admin = $Admin->where($where)->bind($where['id'], $adminId)->find();
        $admin['is_use'] = $is_use;
        return $Admin->save($admin);
    }

    /**
     * 删除关联数据 删除t_admin_role表相关数据
     * @param $adminId
     */
    private function deleteCascade($adminId)
    {
        $where['admin_id'] = ':admin_id';
        $AdminRole = M('admin_role');
        $AdminRole->where($where)->bind($where['admin_id'], $adminId)->delete();
    }

    /**
     * 级联添加 添加到t_admin_role表
     * @param $role_ids
     * @param $adminId
     */
    protected function insertCascade($role_ids, $adminId)
    {
        $AdminRole = M('admin_role');
        foreach ($role_ids as $key => $value) {
            $admin_role['admin_id'] = $adminId;
            $admin_role['role_id'] = $value;
            $AdminRole->add($admin_role);
        }
    }



    //修改密码界面
    public function info()
    {
        $this->display('info');
    }

    //修改密码
    public function re_password()
    {
        $user = session('admin');
        $UserModel = D('Admin');
        $new_password = I('new_password');
        $password = I('password');
        $data = $UserModel->getUsernameAndPassword($user['username'], $password);
        if (!isset($data)) {
            parent::retJson(false,'原始密码错误');
        }
        $_re_password_validate = array(
            array("new_password", 'require', '密码必须填写'),
            array("new_password", '5,10', '密码必须在5-10位数之间', 0, 'length'),
            array("repassword", 'require', '确认密码必须填写'),
            array('repassword', 'new_password', '确认密码不正确', 0, 'confirm'), // 验证确认密码是否和密码一致
        );
        $model = M('Admin');
        if (!M('Admin')->validate($_re_password_validate)->create($_POST)) {
            parent::retJson(false,$model->getError());
        } else {     // 验证通过 可以进行其他数据操作
            $user['password'] = $new_password;
            $user['password'] = md5($user['password'] . C('MD5_KEY'));
            $UserModel->save($user);
            parent::retJson(true, '修改密码成功');
        }
    }

    //重置密码
    public function reset_password(){
        $id = I('id');
        $UserModel = D('Admin');
        $map['id'] = ':id';
        $bind[':id'] = $id;
        $user = $UserModel->where($map)->bind($bind)->find();
        $user['password'] = '123456';
        $user['password'] = md5($user['password'] . C('MD5_KEY'));
        $UserModel->save($user);
    }

}